//
//  SSWBOAuthViewController.swift
//  shanshanlol微博
//
//  Created by 叶竞泽 on 2017/1/19.
//  Copyright © 2017年 JingZe. All rights reserved.
//

import UIKit
import SVProgressHUD

class SSWBOAuthViewController: UIViewController {
    
    // MARK: - 属性
    
    /// 浏览器
    private lazy var webView = UIWebView()
    
    // MARK: - 生命周期
    
    override func loadView() {
        view = webView
        view.backgroundColor = UIColor.white
        // 取消webview的滚动功能 - 新浪返回的授权页面默认是全屏
        webView.scrollView.isScrollEnabled = false
        
        // 设置导航栏
        title = "登录新浪微博"
        // 导航栏按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", target: self, action: #selector(close), isBack: true)
        // 自动填充用户名和密码
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoWriteInfo), isBack: false)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        webView.delegate = self
        
        // 加载授权页面
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirect_url)"
        
        // 建立请求
        guard let url = URL(string: urlString) else {
            return
        }
        
        let urlRequest = URLRequest(url: url)
        
        // 加载请求
        webView.loadRequest(urlRequest)
        
    }
    
    // MARK: - 监听方法
    
    /// 关闭按钮
    @objc fileprivate func close() {
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }
    
    /// 自动填充 - webView 的注入,直接通过js修改本地浏览器中缓存的页面内容
    /// 点击登录按钮执行submit,将本地数据提交给服务器
    @objc private func autoWriteInfo() {
        
        // 准备js,让webView执行
        let jsString = "document.getElementById('userId').value = 'shanshanlol@qq.com';" + "document.getElementById('passwd').value = 'Root@1234567890'"
        webView.stringByEvaluatingJavaScript(from: jsString)
    }

}

extension SSWBOAuthViewController: UIWebViewDelegate {
    
    
    /// 将要加载的请求
    ///
    /// - Parameters:
    ///   - webView: webView
    ///   - request: 要加载的请求
    ///   - navigationType: 导航类型
    /// - Returns: 是否允许加载request
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        
        // 1.如果请求地址包含https://api.weibo.com/oauth2/default.html,就不加载了
        if request.url?.absoluteString.hasPrefix("https://api.weibo.com/oauth2/default.html") == false {
            return true
        }
        // 2.从https://api.weibo.com/oauth2/default.html这个回调地址中查找"code="
        
        // 3.如果有code=,就说明授权成功,否则授权失败
        let codeString = request.url?.query
        if codeString?.hasPrefix("code=") == false {
            print("取消授权")
            close()
            return false
        }
        print("获取授权码...")
        
        // 4.从query字符串中取出授权码 - 此处url中一定有"code"
        let code = codeString?.substring(from: "code=".endIndex) ?? ""
        print("授权码为:\(code)")
        
        // 5.使用code获取accessToken
        SSWBNetworkManager.shared.loadAccessToken(code: code) { (isSuccess) in
            
            if !isSuccess {
                SVProgressHUD.showInfo(withStatus: "网络请求失败")
            } else {
                SVProgressHUD.showSuccess(withStatus: "登录成功...即将跳转到应用程序首页")
                
                // 跳转页面
                
                // 1.授权成功,发送通知,更新页面
                DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + 1, execute: {
                    NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserLogonSuccessNotification), object: self, userInfo: nil)
                    // 2.关闭窗口
                    self.close()
                })
                
            }
        }

        return false
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
}
